package com.sl.au.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.sl.au.entity.Part;
import com.sl.au.entity.PartBaseInfo;
import com.sl.au.entity.GridAreaInfo;
import com.sl.au.entity.Option;
import com.sl.au.service.PartService;
import com.sl.au.service.IdentifyService;
import com.sl.au.service.OptionService;
import com.sl.au.service.UserService;
import com.sl.utils.ExdeUtil;
import com.sl.utils.MsgHelper;

/**
 * 部件管理
 * 
 * @author yangdi
 *
 */
@RestController
@RequestMapping(value = "/ui/part")
public class PartController extends BaseController {

	@Autowired
	PartService partService;
	
	@Autowired
	OptionService optionService;
	
	@Autowired
	UserService userService;
	
	@Autowired
	IdentifyService identifyService;
	
	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView index(){
		ModelAndView modelAndView = this.createLayoutView("part/partindex");
		List<Option> levels = optionService.getRepository().findByGroup("部件层级");
		List<Option> types = optionService.getRepository().findByGroup("部件类别");
		modelAndView.addObject("levels", levels);
		modelAndView.addObject("types", types);
		return modelAndView;
	}
	
	/**
	 * 显示区域结构
	 * @param request
	 * @return
	 */
	@RequestMapping(value="getAllNodes",method = RequestMethod.GET)
	public Map<String,Object> getAllNodes(HttpServletRequest request)
	{
		Map<String,Object> map = new HashMap<String,Object>();
		//List<BussinessLevel> node=null;
		List<Part> node = null;
		
		//node=bussinessLevelService.getAllNodes();
		node = partService.getAllNodes();
		List<Map<String,Object>> nodeMap=new ArrayList<Map<String,Object>>();
		
		nodeMap=partService.getNodeMap(node);
		
		map.put("code", 1);
		map.put("nodes", nodeMap);
	
		return map;
	}
	
	/**
	 * 获取节点信息
	 * @param request
	 * @return
	 */
	@RequestMapping(value="getNode",method = RequestMethod.GET)
	public Map<String,Object> getNode(HttpServletRequest request){
		Map<String,Object> map = new HashMap<String,Object>();
		String Id=request.getParameter("Id");
		Part node = partService.getRepository().findOne(Id);
		map.put("node", node);
		return map;
	}
	
	/**
	 * 初始数据
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "getpage", method = RequestMethod.POST)
	public Map<String,Object> getPage(HttpServletRequest request) {
		Map<String,Object> map = new HashMap<String,Object>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String key=request.getParameter("key");
		List<Part> modules=null;
		long count = 0;
		
		modules = partService.getPartByKey(start, length, key, null, null);
		count=partService.getPartByKeyCount(key);
		
		map.put("data", modules);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}

	/**
	 * 初始数据
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "getchildrenpage", method = RequestMethod.POST)
	public Map<String,Object> getchildrenpage(HttpServletRequest request) {
		Map<String,Object> map = new HashMap<String,Object>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String key=request.getParameter("key");
		String id=request.getParameter("id");
		List<Part> modules=null;
		long count = 0;
		
		modules = partService.getChildrenPartByKey(start, length, id, key, null, null);
		count=partService.getChildrenPartByKeyCount(id, key);
		
		map.put("data", modules);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}
	
	/**
	 * 保存/修改信息
	 * @param map
	 * @return
	 */
	@RequestMapping(value="/save",method = RequestMethod.POST)
	public MsgHelper savePart(@RequestBody Map<String,Object> map){
		MsgHelper msgHelper = null;
		String id = (String) map.get("id");
		String partName = (String) map.get("partName");
		String partIdentify = (String) map.get("partIdentify");
		String partLevelId = (String) map.get("partLevel");
		Option partLevel = optionService.getRepository().findOne(partLevelId);
		String partTypeId = (String) map.get("partType");
		Option partType = optionService.getRepository().findOne(partTypeId);
		
		boolean userShow = ExdeUtil.str2boolean(map.get("userShow"));
		boolean partShow = ExdeUtil.str2boolean( map.get("partShow"));
		boolean gridShow = ExdeUtil.str2boolean( map.get("gridShow"));
		boolean eventShow = ExdeUtil.str2boolean( map.get("eventShow"));
		
		
		Part part = null;
		Part samePart = null;
		if(!id.equals("")){
			part = partService.getRepository().findOne(id);
			samePart = partService.getRepository().findTopByPartParentAndPartIdentify(part.getPartParent(), partIdentify);
			if(part.getPartParent() == null || samePart == null || samePart.getId().equals(id)) {
				part.setUpdateTime(new Date());
				part.setPartName(partName);
				part.setPartIdentify(partIdentify);
				part.setPartLevel(partLevel);
				part.setPartType(partType);
				
				part.setUserShow(userShow);
				part.setPartShow(partShow);
				part.setGridShow(gridShow);
				part.setEventShow(eventShow);
				
				partService.getRepository().save(part);
				msgHelper = MsgHelper.success();
			}else {
				msgHelper = MsgHelper.failed();
				msgHelper.setMsg("此层级存在相同部件编码,不能进行修改!");
			}
		}else{
			part = new Part();
			part.setPartName(partName);
			part.setPartIdentify(partIdentify);
			part.setPartLevel(partLevel);
			part.setPartType(partType);
			
			part.setUserShow(userShow);
			part.setPartShow(partShow);
			part.setGridShow(gridShow);
			part.setEventShow(eventShow);
			
			partService.getRepository().save(part);
			msgHelper = MsgHelper.success();
		}
		
		return msgHelper;
	};
	
	
	/**
	 * 保存部件层级及上传图标
	 * @param part
	 * @param file
	 * @return
	 */
	@RequestMapping(value = "savePartWithFile", method = RequestMethod.POST)
	public MsgHelper saveDetailWithFile(Part part,@RequestParam(value = "file", required = false) MultipartFile file) {
		MsgHelper msgHelper = null;
		if (file.getOriginalFilename() != null && !"".equals(file.getOriginalFilename())) {
			// 注意路径的构建
			String url = getUploadIconFilePath(this.fileUploadPath, "icon/Part", file);
			part.setIconAddress(url);
		}
		
		String partParent = part.getPartParent();
		if(!StringUtils.hasText(partParent)) {
			partParent = null;
		}
		
		Part samePart = null;
		if(!part.getId().equals("")){
			Part oldPart = partService.getRepository().findOne(part.getId());
			samePart = partService.getRepository().findTopByPartParentAndPartIdentify(part.getPartParent(), part.getPartIdentify());
			if(oldPart.getPartParent() == null || samePart == null || samePart.getId().equals(part.getId())) {
				oldPart.setUpdateTime(new Date());
				
				oldPart.setPartName(part.getPartName());
				oldPart.setPartIdentify(part.getPartIdentify());
				oldPart.setPartLevel(part.getPartLevel());
				oldPart.setPartType(part.getPartType());
				
				oldPart.setUserShow(part.isUserShow());
				oldPart.setPartShow(part.isPartShow());
				oldPart.setGridShow(part.isGridShow());
				oldPart.setEventShow(part.isEventShow());
				
				oldPart.setPartParent(partParent);
				oldPart.setIconAddress(part.getIconAddress());

				oldPart.setMemo(part.getMemo());
				
				partService.getRepository().save(oldPart);
				msgHelper = MsgHelper.success();
				msgHelper.setMsg("部件层级保存成功!");
			}else {
				msgHelper = MsgHelper.failed();
				msgHelper.setMsg("此层级存在相同部件编码,不能进行修改!");
			}
		}else{
			if(partParent != null) {
				samePart = partService.getRepository().findTopByPartParentAndPartIdentify(part.getPartParent(), part.getPartIdentify());
				if(samePart == null) {
					Part newPart = new Part();
					
					newPart.setPartName(part.getPartName());
					newPart.setPartIdentify(part.getPartIdentify());
					newPart.setPartLevel(part.getPartLevel());
					newPart.setPartType(part.getPartType());
					
					newPart.setUserShow(part.isUserShow());
					newPart.setPartShow(part.isPartShow());
					newPart.setGridShow(part.isGridShow());
					newPart.setEventShow(part.isEventShow());
					
					newPart.setPartParent(partParent);
					newPart.setIconAddress(part.getIconAddress());
					
					newPart.setMemo(part.getMemo());
					
					int partOrder = partService.getRepository().getPartOrder(partParent);
					newPart.setPartOrder(partOrder);
					partService.getRepository().save(newPart);
					
					msgHelper = MsgHelper.success();
					msgHelper.setMsg("部件层级新增成功!");
				}else {
					msgHelper = MsgHelper.failed();
					msgHelper.setMsg("此层级存在相同部件编码,不能进行新增!");
				}
			}else{
				Part newPart = new Part();
				
				newPart.setPartName(part.getPartName());
				newPart.setPartIdentify(part.getPartIdentify());
				newPart.setPartLevel(part.getPartLevel());
				newPart.setPartType(part.getPartType());
				
				newPart.setUserShow(part.isUserShow());
				newPart.setPartShow(part.isPartShow());
				newPart.setGridShow(part.isGridShow());
				newPart.setEventShow(part.isEventShow());
				
				newPart.setPartParent(partParent);
				newPart.setIconAddress(part.getIconAddress());
				
				newPart.setMemo(part.getMemo());
				
				partService.getRepository().save(newPart);
				msgHelper = MsgHelper.success();
				msgHelper.setMsg("部件层级新增成功!");
			}
		}
		
		return msgHelper;
	}
	
	/**
	 * 删除信息
	 * @param id
	 * @return
	 */
	@RequestMapping("/delete/{id}")
	public MsgHelper deletePart(@PathVariable("id") String id) {
		MsgHelper msgHelper = MsgHelper.success();
		partService.getRepository().delete(id);
		return msgHelper;
	}
	
	/**
	 * 绑定层级关系
	 * @param map
	 * @return
	 */
	@RequestMapping(value="/saveNode",method = RequestMethod.POST)
	public Map<String,Object> saveNode(@RequestBody Map<String,Object> map){
		Map<String,Object> msg = new HashMap<String,Object>();
		String id = (String) map.get("id");
		String parentId = String.valueOf(map.get("parentId"));
		Part part = partService.getRepository().findOne(id);
		Part samePart = partService.getRepository().findTopByPartParentAndPartIdentify(parentId, part.getPartIdentify());
		if(samePart == null) {
			int partOrder = partService.getRepository().getPartOrder(parentId);
			part.setPartOrder(partOrder);
			part.setPartParent(parentId);
			partService.getRepository().save(part);
			msg.put("code", 1);
			msg.put("Part", part);
		}else {
			msg.put("code", 0);
			msg.put("msg", "此层级存在相同部件编码,不能进行绑定!");
		}
		
		return msg;
	};
	
	/**
	 * 移除节点信息
	 * @param map
	 * @return
	 */
	@RequestMapping(value="/deleteNodes")
	public Map deleteNode(@RequestBody Map<String,Object> map)
	{
		String str=String.valueOf(map.get("str"));
		//暂未使用
		//String selectPId= String.valueOf(map.get("selectPId"));
		String ids[]=str.split(",");
		//删除用户信息，暂未处理
		//businesssellerBaseInfoService.deleteBussinessLevel(ids);
		partService.deleteNodes(ids);
		map.put("code", 1);
		return map;
	}
	
	/**
	 * 移动节点信息
	 * @param map
	 * @return
	 */
	@RequestMapping(value="/move")
	public Map moveNode(@RequestBody Map<String,Object> map)
	{
		String id=String.valueOf(map.get("id"));
		String targetId = String.valueOf(map.get("targetId"));
		String moveType = String.valueOf(map.get("moveType"));
		Part targetNode = partService.getRepository().findOne(targetId);
		Part node = partService.getRepository().findOne(id);
		String nodePartParent = node.getPartParent();
		String partParent = null;
		Part samePart = null;
		int partOrder = 0;
		if("inner".equals(moveType)) {
			partParent = targetNode.getId();
			samePart = partService.getRepository().findTopByPartParentAndPartIdentify(partParent, node.getPartIdentify());
			if(samePart == null) {
				node.setPartParent(partParent);
				node.setPartOrder(partOrder);
				partService.getRepository().save(node);
				//更新部件层级信息
				identifyService.updatePartIdentify(id);
			}
		}else {
			partParent = targetNode.getPartParent();
			String oldPartParent = node.getPartParent();
			samePart = partService.getRepository().findTopByPartParentAndPartIdentify(partParent, node.getPartIdentify());
			if(samePart == null || samePart.getId().equals(node.getId())) {
				partOrder = targetNode.getPartOrder();
				if("next".equals(moveType)) {
					partOrder = partOrder + 1;
				}else {
					partOrder = partOrder - 1;
				}
				node.setPartParent(partParent);
				node.setPartOrder(partOrder);
				partService.getRepository().save(node);
				if(!partParent.equals(oldPartParent)) {
					//更新部件层级信息
					identifyService.updatePartIdentify(id);
				}
			}
			
		}
		if(samePart == null || samePart.getId().equals(node.getId())) {
			//拉动之后进行重新排序
			partService.setPartOrder(partParent);
			//原始数据进行排序
			partService.setPartOrder(nodePartParent);
			map.put("code", 1);
		}else {
			map.put("code", 0);
			map.put("msg", "此层级存在相同部件编码,不能进行绑定!");
		}
		return map;
	}
}
